// 全局变量
let currentNote = null;
let reviewCount = 0;
let totalNotes = 0;
let currentNoteReviewed = false; // 标记当前笔记是否已复习

// 聊天相关变量
let chatHistory = [];
let isChatLoading = false;
let currentChatModel = 'gemini-2.5-flash'; // 默认模型，稍后从配置文件更新

let isNoteQaMode = false; // 笔记问答模式开关
let isThinkingMode = false; // 思考模式开关
let noteQaHistory = new Set(); // 跟踪已进行过问答的笔记

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', async function() {
  // 初始化配置
  initConfig();
  
  // 绑定返回按钮事件
  document.getElementById('backBtn').addEventListener('click', function() {
    window.close();
  });
  
  // 绑定导航按钮事件
  document.getElementById('prevBtn').addEventListener('click', function() {
    loadNewRandomNote(true); // 换一条时清空聊天
  });
  
  // 绑定复习按钮事件
  document.getElementById('reviewedBtn').addEventListener('click', markAsReviewed);
  
  // 绑定编辑按钮事件
  document.getElementById('editBtn').addEventListener('click', showEditModal);
  
  // 绑定编辑模态框事件
  document.getElementById('editCancelBtn').addEventListener('click', closeEditModal);
  document.getElementById('editModalMask').addEventListener('click', function(e) {
    if (e.target === this) closeEditModal();
  });
  
  // 绑定编辑表单提交事件
  document.getElementById('editForm').addEventListener('submit', submitEditForm);
  
  // 初始化聊天功能
  initChat();
  
  // 初始化拖拽分隔条
  initResizer();
  
  // 绑定设置按钮事件
  document.getElementById('settingsBtn').addEventListener('click', showChatSettings);
  
  // 绑定模型选择事件
  document.getElementById('modelSelect').addEventListener('change', function(e) {
    currentChatModel = e.target.value;
    saveChatSettings();
    showModelChangeNotification();
  });
  
  // 加载随机笔记数据
  await loadRandomNote();

  // 最大化/还原编辑弹窗逻辑
  const editModal = document.getElementById('editModal');
  const fullscreenToggleBtn = document.getElementById('fullscreenToggleBtn');
  const fullscreenIcon = document.getElementById('fullscreenIcon');
  let isFullscreen = false;

  if (fullscreenToggleBtn && editModal && fullscreenIcon) {
    fullscreenToggleBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      isFullscreen = !isFullscreen;
      if (isFullscreen) {
        editModal.classList.add('fullscreen-modal');
        fullscreenToggleBtn.title = '还原';
        fullscreenIcon.innerHTML = '<path d="M6 16h2v2h8v-2h2v4H6v-4zm12-8h-2V6H8v2H6V4h12v4z"/>';
      } else {
        editModal.classList.remove('fullscreen-modal');
        fullscreenToggleBtn.title = '最大化';
        fullscreenIcon.innerHTML = '<path d="M4 4h7V2H2v9h2V4zm16 0v7h2V2h-9v2h7zm0 16h-7v2h9v-9h-2v7zM4 20v-7H2v9h9v-2H4z"/>';
      }
    });
  }

  // 事件委托：处理思考内容收起/展开
  document.getElementById('chatMessages').addEventListener('click', function(e) {
    if (e.target && e.target.id === 'ai-thinking-toggle') {
      const content = document.getElementById('ai-thinking-content');
      if (!content) return;
      if (content.style.display === 'none') {
        content.style.display = 'block';
        e.target.textContent = '收起思考内容';
      } else {
        content.style.display = 'none';
        e.target.textContent = '展开思考内容';
      }
    }
  });
});

// 初始化配置
function initConfig() {
  // 确保 CONFIG 对象存在
  if (typeof CONFIG !== 'undefined') {
    // 更新默认模型
    currentChatModel = (typeof CONFIG !== 'undefined' && CONFIG.DEFAULT_MODEL) || 'gemini-2.5-flash';
  } else {
    console.warn('⚠️ CONFIG 对象未找到，使用默认配置');
  }
}

// 初始化聊天功能
function initChat() {
  const chatInput = document.getElementById('chatInput');
  const sendBtn = document.getElementById('sendBtn');
  
  // 绑定发送按钮事件
  sendBtn.addEventListener('click', sendChatMessage);
  
  // 绑定输入框回车事件
  chatInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendChatMessage();
    }
  });
  
  // 自动调整输入框高度
  chatInput.addEventListener('input', function() {
    this.style.height = 'auto';
    this.style.height = Math.min(this.scrollHeight, 120) + 'px';
  });
  
  // 绑定笔记问答按钮事件
  document.getElementById('noteQaBtn').addEventListener('click', toggleNoteQaMode);
  
  // 绑定思考模式按钮事件
  document.getElementById('thinkingBtn').addEventListener('click', toggleThinkingMode);
  
  // 初始化模型选择框
  initModelSelect();
  
  // 从本地存储恢复设置
  loadChatSettings();
  
  // 验证配置
  if (typeof validateConfig === 'function' && !validateConfig()) {
    showChatError('请在 config.js 中设置有效的 Gemini API Key');
  } else if (typeof CONFIG === 'undefined' || !CONFIG.GEMINI_API_KEY || CONFIG.GEMINI_API_KEY === 'YOUR_GEMINI_API_KEY_HERE') {
    showChatError('请在 config.js 中设置有效的 Gemini API Key');
  }
}

// 切换笔记问答模式
function toggleNoteQaMode() {
  isNoteQaMode = !isNoteQaMode;
  updateQaModeUI();
  saveChatSettings(); // 保存设置
  
  // 显示模式切换通知
  const chatMessages = document.getElementById('chatMessages');
  const notificationDiv = document.createElement('div');
  notificationDiv.className = 'message assistant';
  
  if (isNoteQaMode) {
    if (!currentNote) {
      showChatError('当前没有笔记内容，请先加载一条笔记');
      isNoteQaMode = false;
      updateQaModeUI();
      return;
    }
    
    // 如果切换到笔记问答模式，清空聊天历史和问答历史
    chatHistory = [];
    noteQaHistory.clear();
    chatMessages.innerHTML = '';
    addClearChatButton();
    
    notificationDiv.innerHTML = `
      <div class="message-content" style="background: #d4edda; color: #155724; border-color: #c3e6cb;">
        📝 已切换到笔记问答模式，AI将基于当前笔记内容回答你的问题
      </div>
    `;
  } else {
    notificationDiv.innerHTML = `
      <div class="message-content" style="background: #e3f2fd; color: #1976d2; border-color: #1976d2;">
        💬 已切换到普通对话模式，AI将进行一般性对话
      </div>
    `;
  }
  
  chatMessages.appendChild(notificationDiv);
  scrollChatToBottom();
  
  // 3秒后自动移除通知
  setTimeout(() => {
    if (notificationDiv.parentNode) {
      notificationDiv.remove();
    }
  }, (typeof CONFIG !== 'undefined' && CONFIG.CHAT && CONFIG.CHAT.MODEL_CHANGE_NOTIFICATION_DURATION) || 3000);
}

// 更新问答模式UI
function updateQaModeUI() {
  const qaBtn = document.getElementById('noteQaBtn');
  const chatInput = document.getElementById('chatInput');
  
  if (isNoteQaMode) {
    qaBtn.style.background = '#28a745';
    qaBtn.style.color = 'white';
    qaBtn.style.borderColor = '#28a745';
    chatInput.placeholder = '请输入关于当前笔记的问题...';
  } else {
    qaBtn.style.background = '#e9ecef';
    qaBtn.style.color = '#495057';
    qaBtn.style.borderColor = '#ced4da';
    chatInput.placeholder = '请输入你的问题...';
  }
}

// 切换思考模式
function toggleThinkingMode() {
  isThinkingMode = !isThinkingMode;
  updateThinkingModeUI();
  saveChatSettings(); // 保存设置
  
  // 显示模式切换通知
  const chatMessages = document.getElementById('chatMessages');
  const notificationDiv = document.createElement('div');
  notificationDiv.className = 'message assistant';
  
  if (isThinkingMode) {
    notificationDiv.innerHTML = `
      <div class="message-content" style="background: #fff3cd; color: #856404; border-color: #ffeaa7;">
        🧠 已开启思考模式，AI将展示思考过程
      </div>
    `;
  } else {
    notificationDiv.innerHTML = `
      <div class="message-content" style="background: #e3f2fd; color: #1976d2; border-color: #1976d2;">
        💭 已关闭思考模式，AI将直接回答问题
      </div>
    `;
  }
  
  chatMessages.appendChild(notificationDiv);
  scrollChatToBottom();
  
  // 3秒后自动移除通知
  setTimeout(() => {
    if (notificationDiv.parentNode) {
      notificationDiv.remove();
    }
  }, (typeof CONFIG !== 'undefined' && CONFIG.CHAT && CONFIG.CHAT.MODEL_CHANGE_NOTIFICATION_DURATION) || 3000);
}

// 更新思考模式UI
function updateThinkingModeUI() {
  const thinkingBtn = document.getElementById('thinkingBtn');
  
  if (isThinkingMode) {
    thinkingBtn.style.background = '#ffc107';
    thinkingBtn.style.color = '#212529';
    thinkingBtn.style.borderColor = '#ffc107';
  } else {
    thinkingBtn.style.background = '#e9ecef';
    thinkingBtn.style.color = '#495057';
    thinkingBtn.style.borderColor = '#ced4da';
  }
}

// 初始化模型选择框
function initModelSelect() {
  const modelSelect = document.getElementById('modelSelect');
  if (!modelSelect) return;
  
  // 清空现有选项
  modelSelect.innerHTML = '';
  
  // 从配置文件获取可用模型
  const availableModels = getAvailableModels();
  
  // 添加模型选项
  availableModels.forEach(modelKey => {
    const option = document.createElement('option');
    option.value = modelKey;
    option.textContent = getModelDisplayName(modelKey);
    modelSelect.appendChild(option);
  });
}

// 加载聊天设置
function loadChatSettings() {
  const savedModel = localStorage.getItem('review_chat_model');
  if (savedModel && (typeof CONFIG !== 'undefined' && CONFIG.MODELS && CONFIG.MODELS[savedModel])) {
    currentChatModel = savedModel;
  } else if (savedModel && !CONFIG.MODELS[savedModel]) {
    // 如果保存的模型不存在，回退到默认模型
    currentChatModel = (typeof CONFIG !== 'undefined' && CONFIG.DEFAULT_MODEL) || 'gemini-2.5-flash';
    localStorage.setItem('review_chat_model', currentChatModel);
    console.log(`已删除的模型 ${savedModel} 不存在，已回退到默认模型 ${currentChatModel}`);
  }
  

  
  // 加载问答模式状态
  const savedQaMode = localStorage.getItem('review_qa_mode');
  if (savedQaMode !== null) {
    isNoteQaMode = savedQaMode === 'true';
  }
  
  // 加载思考模式状态
  const savedThinkingMode = localStorage.getItem('review_thinking_mode');
  if (savedThinkingMode !== null) {
    isThinkingMode = savedThinkingMode === 'true';
  }
  
  // 更新模型选择框
  const modelSelect = document.getElementById('modelSelect');
  if (modelSelect) {
    modelSelect.value = currentChatModel;
  }
  
  // 更新UI状态
  updateQaModeUI();
  updateThinkingModeUI();
}

// 保存聊天设置
function saveChatSettings() {
  localStorage.setItem('review_chat_model', currentChatModel);
  localStorage.setItem('review_qa_mode', isNoteQaMode);
  localStorage.setItem('review_thinking_mode', isThinkingMode);
}

// 添加聊天消息到界面
function appendChatMessage(sender, text, isTyping = false) {
  const chatMessages = document.getElementById('chatMessages');
  
  // 如果是第一条消息，清除欢迎信息
  if (chatMessages.querySelector('.welcome-message')) {
    chatMessages.innerHTML = '';
  }
  
  const messageDiv = document.createElement('div');
  messageDiv.className = `message ${sender}`;
  
  const contentDiv = document.createElement('div');
  contentDiv.className = 'message-content';
  
  if (isTyping) {
    const duration = (typeof CONFIG !== 'undefined' && CONFIG.CHAT && CONFIG.CHAT.TYPING_ANIMATION_DURATION) || 1400 / 1000;
    contentDiv.innerHTML = `
      <div style="display: flex; align-items: center; gap: 4px;">
        <div style="width: 8px; height: 8px; background: #999; border-radius: 50%; animation: typing ${duration}s infinite ease-in-out;"></div>
        <div style="width: 8px; height: 8px; background: #999; border-radius: 50%; animation: typing ${duration}s infinite ease-in-out 0.2s;"></div>
        <div style="width: 8px; height: 8px; background: #999; border-radius: 50%; animation: typing ${duration}s infinite ease-in-out 0.4s;"></div>
      </div>
    `;
  } else {
    // 格式化思考模式的消息
    if (sender === 'assistant' && isThinkingMode) {
      contentDiv.innerHTML = formatThinkingMessage(text);
    } else if (sender === 'assistant') {
      contentDiv.innerHTML = marked.parse(text);
    } else {
      contentDiv.textContent = text;
    }
  }
  
  messageDiv.appendChild(contentDiv);
  chatMessages.appendChild(messageDiv);
  scrollChatToBottom();
  
  return messageDiv;
}

// 格式化思考模式消息
function formatThinkingMessage(text) {
  if (!text) return '';
  // 检查是否包含思考过程
  const thinkingMatch = text.match(/🤔\s*思考过程：([\s\S]*?)(?=💡\s*答案：|$)/);
  const answerMatch = text.match(/💡\s*答案：([\s\S]*)/);
  let formattedText = '';
  if (thinkingMatch) {
    const thinkingContent = thinkingMatch[1].trim();
    formattedText += `
      <div id=\"ai-thinking-fold\" style=\"background: #fff3cd; border-left: 4px solid #ffc107; padding: 12px; margin-bottom: 12px; border-radius: 4px; position: relative;\">\n        <div style=\"font-weight: bold; color: #856404; margin-bottom: 8px; cursor:pointer; user-select:none;\">🤔 思考过程： <span id='ai-thinking-toggle' style=\"font-size:12px; color:#856404; margin-left:8px;\">收起思考内容</span></div>\n        <div id='ai-thinking-content' style=\"color: #856404; line-height: 1.5; display: block;\">${marked.parse(thinkingContent)}</div>\n      </div>\n    `;
  }
  if (answerMatch) {
    const answerContent = answerMatch[1].trim();
    formattedText += `
      <div style=\"background: #d4edda; border-left: 4px solid #28a745; padding: 12px; border-radius: 4px;\">\n        <div style=\"font-weight: bold; color: #155724; margin-bottom: 8px;\">💡 答案：</div>\n        <div style=\"color: #155724; line-height: 1.5;\">${marked.parse(answerContent)}</div>\n      </div>\n    `;
  }
  if (!formattedText) {
    formattedText = marked.parse(text);
  }
  return formattedText;
}

// 格式化思考模式响应（包含思考摘要）
function formatThinkingResponse(text, thinkingSummary) {
  let formattedText = '';
  
  // 添加思考摘要
  if (thinkingSummary) {
    formattedText += `<div style="background: #f8f9fa; border-left: 4px solid #007bff; padding: 12px; margin-bottom: 12px; border-radius: 4px;">
      <div style="font-weight: bold; color: #007bff; margin-bottom: 8px;">🧠 思考摘要</div>
      <div style="color: #495057; line-height: 1.5;">${thinkingSummary.replace(/\n/g, '<br>')}</div>
    </div>`;
  }
  
  // 添加最终答案
  formattedText += `<div style="background: #e8f5e8; border-left: 4px solid #28a745; padding: 12px; border-radius: 4px;">
    <div style="font-weight: bold; color: #28a745; margin-bottom: 8px;">💡 最终答案</div>
    <div style="color: #155724; line-height: 1.5;">${text.replace(/\n/g, '<br>')}</div>
  </div>`;
  
  return formattedText;
}

// 滚动聊天到底部
function scrollChatToBottom() {
  const chatMessages = document.getElementById('chatMessages');
  chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 显示聊天错误消息
function showChatError(message) {
  const chatMessages = document.getElementById('chatMessages');
  
  const errorDiv = document.createElement('div');
  errorDiv.className = 'message assistant';
  errorDiv.innerHTML = `
    <div class="message-content" style="background: #ffebee; color: #c62828; border-color: #ffcdd2;">
      ❌ ${message}
    </div>
  `;
  chatMessages.appendChild(errorDiv);
  scrollChatToBottom();
  
  // 从配置文件获取错误消息持续时间
  setTimeout(() => {
    if (errorDiv.parentNode) {
      errorDiv.remove();
    }
  }, (typeof CONFIG !== 'undefined' && CONFIG.CHAT && CONFIG.CHAT.ERROR_MESSAGE_DURATION) || 3000);
}

// 设置聊天加载状态
function setChatLoading(loading) {
  isChatLoading = loading;
  const sendBtn = document.getElementById('sendBtn');
  const chatInput = document.getElementById('chatInput');
  
  sendBtn.disabled = loading;
  chatInput.disabled = loading;
  
  if (loading) {
    sendBtn.textContent = '发送中...';
  } else {
    sendBtn.textContent = '发送';
  }
}

// 发送聊天消息
async function sendChatMessage() {
  const chatInput = document.getElementById('chatInput');
  const userMsg = chatInput.value.trim();
  
  if (!userMsg || isChatLoading) {
    return;
  }
  
  // 添加用户消息
  appendChatMessage('user', userMsg);
  chatInput.value = '';
  chatInput.style.height = 'auto';
  
  // 添加助手消息（带打字指示器）
  const assistantMessage = appendChatMessage('assistant', '', true);
  
  // 设置加载状态
  setChatLoading(true);
  
  try {
    // 添加用户消息到对话历史
    chatHistory.push({
      role: 'user',
      parts: [{ text: userMsg }]
    });
    
    // 调用 Gemini API
    const response = await callGeminiAPI();
    
    if (response.success) {
      // 流式输出已经更新了消息内容，只需要保存对话历史
      chatHistory.push({
        role: 'model',
        parts: [{ text: response.text }]
      });
      
      // 新增：保存AI问答历史
      // saveAiQaHistory({
      //   note_id: currentNote && currentNote['主键'],
      //   user_question: userMsg,
      //   model_answer: response.text,
      //   model_used: currentChatModel
      // });
      
      // 在笔记问答模式下，第一次问答后需要更新聊天历史中的用户问题
      if (isNoteQaMode && currentNote && noteQaHistory.has(currentNote['主键'])) {
        // 检查是否是第一次问答的AI回答
        const isFirstResponse = chatHistory.length === 2; // 用户问题 + AI回答
        if (isFirstResponse) {
          // 第一次笔记问答完成，聊天历史已更新
          console.log('第一次笔记问答完成，聊天历史已更新');
        }
      }
    } else {
      // 移除打字指示器并显示错误
      assistantMessage.remove();
      showChatError(response.error);
    }
  } catch (error) {
    assistantMessage.remove();
    showChatError(`请求失败: ${error.message}`);
  } finally {
    setChatLoading(false);
  }
}

// 新增：保存AI问答历史到后端
async function saveAiQaHistory({ note_id, user_question, model_answer, model_used }) {
  if (!note_id || !user_question || !model_used) return;
  try {
    await fetch('http://127.0.0.1:3000/api/ai_qa_history', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        note_id,
        user_question,
        model_answer,
        model_used
      })
    });
  } catch (e) {
    console.warn('保存AI问答历史失败', e);
  }
}

// 调用 Gemini API
async function callGeminiAPI() {
  // 从配置文件获取 API Key
  const apiKey = getApiKey();
  
  if (!apiKey || apiKey === 'YOUR_GEMINI_API_KEY_HERE') {
    return {
      success: false,
      error: '请在 config.js 中设置有效的 Gemini API Key'
    };
  }
  
  const url = `https://generativelanguage.googleapis.com/v1beta/models/${currentChatModel}:streamGenerateContent?key=${apiKey}&alt=sse`;
  
  if (isNoteQaMode && currentNote) {
    // 笔记问答模式
    return await handleNoteQaMode(url);
  } else {
    // 普通对话模式
    return await handleNormalChatMode(url);
  }
}

// 处理笔记问答模式
async function handleNoteQaMode(url) {
  try {
    // 检查是否是第一次针对当前笔记的问答
    const isFirstQuestion = !noteQaHistory.has(currentNote['主键']);
    
    if (isFirstQuestion) {
      // 第一次问答：使用prompt.md模板
      const userQuestion = chatHistory[chatHistory.length - 1]?.parts[0]?.text || '';
      const fullPrompt = await buildNoteQaPrompt(currentNote, userQuestion);
      
      const requestBody = {
        contents: [
          {
            role: 'user',
            parts: [{ text: fullPrompt }]
          }
        ]
      };
      
      const response = await sendGeminiRequest(url, requestBody);
      
      // 如果成功，记录当前笔记已进行过问答，并更新聊天历史
      if (response.success) {
        noteQaHistory.add(currentNote['主键']);
        
        // 将第一次的完整prompt替换掉原来的用户问题
        chatHistory[chatHistory.length - 1] = {
          role: 'user',
          parts: [{ text: fullPrompt }]
        };
      }
      
      return response;
      
    } else {
      // 后续问答：使用历史对话
      const requestBody = {
        contents: chatHistory
      };
      
      return await sendGeminiRequest(url, requestBody);
    }
    
  } catch (error) {
    console.error('笔记问答模式处理失败:', error);
    // 回退到原来的方式
    const systemPrompt = `你是一个学习助手，专门帮助用户理解和记忆笔记内容。

当前笔记信息：
标题：${currentNote['标题'] || '无标题'}
类型：${currentNote['类型'] || '未分类'}
关键词：${currentNote['关键词'] || '无'}
来源：${currentNote['来源'] || '未知'}
内容：${currentNote['内容'] || '暂无内容'}
思考：${currentNote['思考'] || '暂无思考'}

请基于这个笔记内容来回答用户的问题，帮助用户更好地理解和记忆。如果用户的问题与笔记内容无关，请礼貌地提醒用户当前是笔记问答模式。`;
    
    const requestBody = {
      contents: [
        {
          role: 'user',
          parts: [{ text: systemPrompt }]
        },
        ...chatHistory
      ]
    };
    
    return await sendGeminiRequest(url, requestBody);
  }
}

// 处理普通对话模式
async function handleNormalChatMode(url) {
  const systemPrompt = '你是一个友好的AI助手，可以帮助用户进行各种对话和交流。请用中文回答用户的问题。';
  
  const requestBody = {
    contents: [
      {
        role: 'user',
        parts: [{ text: systemPrompt }]
      },
      ...chatHistory
    ]
  };

  return await sendGeminiRequest(url, requestBody);
}

// 发送Gemini API请求
async function sendGeminiRequest(url, requestBody) {
  try {
    // 流式思考模式参数
    if (isThinkingMode) {
      if (!requestBody.generationConfig) {
        requestBody.generationConfig = {};
      }
      requestBody.generationConfig.thinkingConfig = {
        includeThoughts: true,
        thinkingBudget: -1
      };
    }
    
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody)
    });

    if (!response.ok) {
      const errorData = await response.json();
      // 处理 API 错误
      if (response.status === 400) {
        return {
          success: false,
          error: '请求格式错误，请检查输入内容'
        };
      } else if (response.status === 401) {
        return {
          success: false,
          error: 'API Key 无效，请检查并重新输入'
        };
      } else if (response.status === 429) {
        return {
          success: false,
          error: '请求过于频繁，请稍后再试'
        };
      } else if (response.status === 403) {
        return {
          success: false,
          error: 'API Key 权限不足或已过期'
        };
      } else {
        return {
          success: false,
          error: `API 错误 (${response.status}): ${errorData.error?.message || '未知错误'}`
        };
      }
    }

    // 处理流式响应 (Server-Sent Events)
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let fullText = '';
    let isFirstChunk = true;
    // 新增：思考过程和答案分开拼接
    let streamingThoughts = '';
    let streamingAnswer = '';

    // 记录本次提问内容
    let userQuestion = '';
    if (requestBody.contents && requestBody.contents.length > 0) {
      // 普通对话模式
      if (requestBody.contents[requestBody.contents.length-1].role === 'user') {
        userQuestion = requestBody.contents[requestBody.contents.length-1].parts[0].text;
      } else if (requestBody.contents.length > 1 && requestBody.contents[requestBody.contents.length-2].role === 'user') {
        userQuestion = requestBody.contents[requestBody.contents.length-2].parts[0].text;
      }
    }

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      const chunk = decoder.decode(value);
      const lines = chunk.split('\n');
      for (const line of lines) {
        if (line.trim() === '') continue;
        if (line.startsWith('data: ')) {
          const dataStr = line.slice(6);
          if (dataStr === '[DONE]') continue;
          try {
            const data = JSON.parse(dataStr);
            if (data.candidates && data.candidates[0] && data.candidates[0].content && data.candidates[0].content.parts) {
              for (const part of data.candidates[0].content.parts) {
                if (!part.text) continue;
                
                // 根据官方文档，part.thought为true时是思考过程，否则是最终答案
                if (isThinkingMode && part.thought === true) {
                  streamingThoughts += part.text;
                  console.log('思考过程:', part.text);
                } else {
                  streamingAnswer += part.text;
                  console.log('最终答案:', part.text);
                }
                
                // 实时渲染
                updateStreamingChatMessage(streamingAnswer, streamingThoughts);
              }
            }
          } catch (e) {
            // 忽略解析错误，继续处理下一个块
            console.log('解析流式数据时出错:', e, '数据:', dataStr);
            continue;
          }
        }
      }
    }
    if (!streamingAnswer && !streamingThoughts) {
      return { success: false, error: 'AI 未返回有效内容' };
    }

    // 只在流式输出完全结束后调用一次保存接口
    saveAiQaHistory({
      note_id: currentNote && currentNote['主键'],
      user_question: userQuestion,
      model_answer: streamingAnswer,
      model_used: currentChatModel
    });

    return {
      success: true,
      text: streamingAnswer,
      thinkingSummary: streamingThoughts
    };

  } catch (error) {
    if (error.name === 'TypeError' && error.message.includes('fetch')) {
      return {
        success: false,
        error: '网络连接失败，请检查网络设置'
      };
    }
    throw error;
  }
}

// 更新流式消息内容（支持思考模式分区渲染）
function updateStreamingChatMessage(answer, thoughts) {
  const chatMessages = document.getElementById('chatMessages');
  const lastMessage = chatMessages.lastElementChild;
  if (lastMessage && lastMessage.classList.contains('assistant')) {
    const contentDiv = lastMessage.querySelector('.message-content');
    if (contentDiv) {
      if (isThinkingMode) {
        // 分区渲染思考过程和答案，思考内容折叠
        let html = '';
        if (thoughts) {
          html += `<div id="ai-thinking-fold" style=\"background: #f8f9fa; border-left: 4px solid #007bff; padding: 12px; margin-bottom: 12px; border-radius: 4px; position: relative;\">`
            + `<div style=\"font-weight: bold; color: #007bff; margin-bottom: 8px; cursor:pointer; user-select:none;\">🧠 思考过程 <span id='ai-thinking-toggle' style=\"font-size:12px; color:#007bff; margin-left:8px;\">收起思考内容</span></div>`
            + `<div id='ai-thinking-content' style=\"color: #495057; line-height: 1.5; display: block;\">${marked.parse(thoughts)}</div>`
            + `</div>`;
        }
        if (answer) {
          html += `<div style=\"background: #e8f5e8; border-left: 4px solid #28a745; padding: 12px; border-radius: 4px;\">`
            + `<div style=\"font-weight: bold; color: #28a745; margin-bottom: 8px;\">💡 最终答案</div>`
            + `<div style=\"color: #155724; line-height: 1.5;\">${marked.parse(answer)}</div></div>`;
        }
        contentDiv.innerHTML = html;
        // --- 自动折叠思考内容 ---
        if (answer && thoughts) {
          const thinkingContent = document.getElementById('ai-thinking-content');
          const thinkingToggle = document.getElementById('ai-thinking-toggle');
          if (thinkingContent && thinkingToggle && thinkingContent.style.display !== 'none') {
            thinkingContent.style.display = 'none';
            thinkingToggle.textContent = '展开思考内容';
          }
        }
      } else {
        contentDiv.innerHTML = marked.parse(answer);
      }
      scrollChatToBottom();
    }
  }
}

// 清空聊天记录
function clearChat() {
  const chatMessages = document.getElementById('chatMessages');
  chatMessages.innerHTML = `
    <div class="welcome-message">
      <p>👋 你好！我是你的AI学习助手</p>
      <p>你可以点击"📝 笔记问答"按钮切换到笔记问答模式，或直接进行普通对话</p>
      <p>点击"🧠 思考模式"按钮可以查看AI的思考过程</p>
    </div>
  `;
  chatHistory = [];
  noteQaHistory.clear(); // 清空问答历史
  
  // 重置模式
  isNoteQaMode = false;
  isThinkingMode = false;
  updateQaModeUI();
  updateThinkingModeUI();
}

// 添加清空聊天按钮
function addClearChatButton() {
  const clearBtn = document.createElement('button');
  clearBtn.textContent = '🗑️ 清空聊天';
  clearBtn.style.cssText = `
    position: absolute;
    top: 15px;
    right: 20px;
    padding: 4px 8px;
    background: rgba(255,255,255,0.9);
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    z-index: 1000;
  `;
  clearBtn.onclick = () => {
    if (confirm('确定要清空所有聊天记录吗？')) {
      clearChat();
    }
  };
  
  // 添加到右侧面板
  const rightPanel = document.querySelector('.right-panel');
  rightPanel.style.position = 'relative';
  rightPanel.appendChild(clearBtn);
}

// 页面加载完成后添加清空按钮
setTimeout(addClearChatButton, 1000);

// 显示聊天设置
function showChatSettings() {
  const currentApiKey = getApiKey();
  const isConfigured = currentApiKey && currentApiKey !== 'YOUR_GEMINI_API_KEY_HERE';
  
  let message = '当前配置信息：\n\n';
  message += `API Key: ${isConfigured ? '✅ 已配置' : '❌ 未配置'}\n`;
  message += `默认模型: ${getModelDisplayName(currentChatModel)}\n`;
  message += `流式输出: ${typeof CONFIG !== 'undefined' && CONFIG.USE_STREAMING ? '开启' : '关闭'}\n`;
  message += `服务器地址: ${typeof CONFIG !== 'undefined' && CONFIG.SERVER_URL || ''}\n`;
  message += `当前模式: ${isNoteQaMode ? '笔记问答模式' : '普通对话模式'}\n`;
  message += `思考模式: ${isThinkingMode ? '开启' : '关闭'}\n\n`;
  message += '如需修改配置，请编辑 config.js 文件。';
  
  alert(message);
}

// 显示模型切换通知
function showModelChangeNotification() {
  const chatMessages = document.getElementById('chatMessages');
  
  const notificationDiv = document.createElement('div');
  notificationDiv.className = 'message assistant';
  notificationDiv.innerHTML = `
    <div class="message-content" style="background: #e3f2fd; color: #1976d2; border-color: #1976d2;">
      🔄 已切换到 ${getModelDisplayName(currentChatModel)} 模型
    </div>
  `;
  chatMessages.appendChild(notificationDiv);
  scrollChatToBottom();
  
  // 从配置文件获取通知持续时间
  setTimeout(() => {
    if (notificationDiv.parentNode) {
      notificationDiv.remove();
    }
  }, (typeof CONFIG !== 'undefined' && CONFIG.CHAT && CONFIG.CHAT.MODEL_CHANGE_NOTIFICATION_DURATION) || 3000);
}

// 加载随机笔记数据
async function loadRandomNote() {
  try {
    // 从URL参数中获取指定的笔记ID
    const urlParams = new URLSearchParams(window.location.search);
    const specificNoteId = urlParams.get('noteId');
    
    if (specificNoteId) {
      console.log('检测到URL参数中的笔记ID:', specificNoteId);
      
      // 显示加载状态
      document.getElementById('loading').style.display = 'block';
      document.getElementById('noteDisplay').style.display = 'none';
      document.getElementById('loading').textContent = '正在加载指定笔记...';
      
      // 重新查询数据库获取指定笔记
      // 使用detail接口获取完整数据
      const response = await fetch(`http://127.0.0.1:3000/api/notes/${specificNoteId}/detail`);
      const result = await response.json();
      
      if (result.success) {
        currentNote = result.data;
        if (currentNote) {
          // 数据字段名转换，确保与复习页面期望的字段名一致
          const convertedNote = {
            '主键': currentNote['主键'] || specificNoteId,
            '标题': currentNote['标题'] || currentNote['title'] || '无标题',
            '类型': currentNote['类型'] || currentNote['type'] || '未分类',
            '关键词': currentNote['关键词'] || currentNote['key_list'] || currentNote['keywords'] || '无',
            '来源': currentNote['来源'] || currentNote['source'] || '未知',
            '创建时间': currentNote['创建时间'] || currentNote['created_at'] || '未知',
            '内容': currentNote['内容'] || currentNote['content'] || '暂无内容',
            '思考': currentNote['思考'] || currentNote['think'] || currentNote['thoughts'] || '暂无思考',
            '复习次数': currentNote['复习次数'] || currentNote['review_count'] || 0
          };
          
          currentNote = convertedNote;
          currentNoteReviewed = false; // 重置复习状态
          showNoteDisplay();
          showCurrentNote();
          console.log('成功加载指定笔记:', currentNote);
          console.log('笔记标题:', currentNote['标题']);
          console.log('笔记类型:', currentNote['类型']);
          console.log('笔记关键词:', currentNote['关键词']);
          console.log('笔记来源:', currentNote['来源']);
          console.log('笔记创建时间:', currentNote['创建时间']);
          
          // 更新页面标题，显示正在复习指定笔记
          const headerTitle = document.querySelector('.header h1');
          if (headerTitle) {
            headerTitle.innerHTML = `📚 复习笔记 - ${currentNote['标题']}`;
          }
        } else {
          showError('指定笔记不存在');
        }
      } else {
        showError('加载指定笔记失败：' + result.message);
      }
    } else {
      // 显示加载状态
      document.getElementById('loading').style.display = 'block';
      document.getElementById('noteDisplay').style.display = 'none';
      document.getElementById('loading').textContent = '正在获取随机笔记...';
      
      const response = await fetch('http://127.0.0.1:3000/api/notes/random');
      const result = await response.json();
      
      if (result.success) {
        currentNote = result.data;
        if (currentNote) {
          currentNoteReviewed = false; // 重置复习状态
          showNoteDisplay();
          showCurrentNote();
        } else {
          showNoNotes();
        }
      } else {
        showError('加载笔记失败：' + result.message);
      }
    }
  } catch (error) {
    console.error('加载笔记失败:', error);
    showError('网络连接失败，请检查服务是否启动');
  }
}

// 显示笔记内容区域
function showNoteDisplay() {
  document.getElementById('loading').style.display = 'none';
  document.getElementById('noteDisplay').style.display = 'block';
}

// 显示无笔记提示
function showNoNotes() {
  document.getElementById('loading').style.display = 'none';
  document.getElementById('noteDisplay').style.display = 'block';
  document.getElementById('noteDisplay').innerHTML = `
    <div style="text-align: center; padding: 50px 0; color: #666;">
      <div style="font-size: 48px; margin-bottom: 20px;">📝</div>
      <div style="font-size: 18px; margin-bottom: 10px;">暂无笔记</div>
      <div style="font-size: 14px;">请先添加一些笔记后再来复习</div>
    </div>
  `;
}

// 显示错误信息
function showError(message) {
  document.getElementById('loading').style.display = 'none';
  document.getElementById('noteDisplay').style.display = 'block';
  document.getElementById('noteDisplay').innerHTML = `
    <div style="text-align: center; padding: 50px 0; color: #d32f2f;">
      <div style="font-size: 48px; margin-bottom: 20px;">❌</div>
      <div style="font-size: 16px;">${message}</div>
    </div>
  `;
}

// 显示当前笔记
function showCurrentNote() {
  if (!currentNote) return;

  // 更新笔记元信息
  document.getElementById('noteTitle').textContent = currentNote['标题'] || '无标题';
  document.getElementById('noteType').textContent = `类型：${currentNote['类型'] || '未分类'}`;
  document.getElementById('noteKeywords').textContent = `关键词：${currentNote['关键词'] || '无'}`;
  document.getElementById('noteSource').textContent = `来源：${currentNote['来源'] || '未知'}`;
  document.getElementById('noteDate').textContent = `创建时间：${currentNote['创建时间'] || '未知'}`;
  document.getElementById('noteReviewCount').textContent = `该笔记复习：${currentNote['复习次数'] || 0} 次`;
  
  // 更新笔记内容
  const content = currentNote['内容'] || '暂无内容';
  document.getElementById('noteContent').innerHTML = marked.parse(content);
  
  // 更新思考内容
  const thoughts = currentNote['思考'] || '暂无思考';
  document.getElementById('noteThoughts').innerHTML = marked.parse(thoughts);
  
  // 更新按钮状态
  updateNavigationButtons();
}

// 更新导航按钮状态
function updateNavigationButtons() {
  const prevBtn = document.getElementById('prevBtn');
  const reviewedBtn = document.getElementById('reviewedBtn');
  
  // 在随机复习模式下，按钮可用
  prevBtn.disabled = false;
  
  // 更新按钮文本
  prevBtn.textContent = '换一条';
  
  // 更新复习按钮状态
  if (currentNoteReviewed) {
    reviewedBtn.textContent = '✅ 已复习';
    reviewedBtn.style.backgroundColor = '#6c757d';
    reviewedBtn.disabled = true;
  } else {
    reviewedBtn.textContent = '✅ 我已复习';
    reviewedBtn.style.backgroundColor = '#28a745';
    reviewedBtn.disabled = false;
  }
}

// 加载新的随机笔记
async function loadNewRandomNote(shouldClearChat = true) {
  // 只有在需要时才清空聊天历史和问答历史
  if (shouldClearChat) {
    chatHistory = [];
    noteQaHistory.clear();
    // 清空聊天界面
    const chatMessages = document.getElementById('chatMessages');
    chatMessages.innerHTML = '';
    // 添加清空聊天按钮
    addClearChatButton();
  }

  // 清除URL参数，切换到随机复习模式
  const currentUrl = new URL(window.location);
  currentUrl.searchParams.delete('noteId');
  window.history.replaceState({}, '', currentUrl);
  
  // 恢复默认标题
  const headerTitle = document.querySelector('.header h1');
  if (headerTitle) {
    headerTitle.innerHTML = '📚 复习笔记';
  }
  
  await loadRandomNote();
}

// 标记当前笔记为已复习
async function markAsReviewed() {
  if (!currentNote || currentNoteReviewed) return;
  
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${currentNote['主键']}/review`, {
      method: 'POST'
    });
    const result = await response.json();
    
    if (result.success) {
      currentNoteReviewed = true;
      reviewCount++;
      // 更新当前笔记的复习次数
      currentNote['复习次数'] = (currentNote['复习次数'] || 0) + 1;
      updateNavigationButtons();
      showCurrentNote();
      
      // 显示成功提示
      const reviewedBtn = document.getElementById('reviewedBtn');
      reviewedBtn.textContent = '✅ 复习成功！';
      
      // 延迟1秒后自动换一条笔记（不清空聊天）
      setTimeout(async () => {
        await loadNewRandomNote(false);
      }, 1000);
    } else {
      alert('标记复习失败：' + result.message);
    }
  } catch (error) {
    console.error('标记复习失败:', error);
    alert('标记复习失败，请检查网络连接');
  }
}

// 获取笔记类型列表
async function fetchNoteTypes() {
  try {
    const response = await fetch('http://127.0.0.1:3000/api/note_types');
    const result = await response.json();
    if (result.success && Array.isArray(result.data)) {
      return result.data;
    }
    return [];
  } catch (e) {
    return [];
  }
}

// 渲染类型下拉框
function renderTypeSelect(selectEl, types, selectedValue) {
  selectEl.innerHTML = '<option value="">请选择类型</option>' +
    types.map(type => `<option value="${type}">${type}</option>`).join('');
  if (selectedValue) selectEl.value = selectedValue;
}

// 显示编辑模态框
async function showEditModal() {
  if (!currentNote) return;
  const mask = document.getElementById('editModalMask');
  mask.style.display = 'flex';
  document.getElementById('editId').value = currentNote['主键'];
  // 动态填充类型下拉框
  const types = await fetchNoteTypes();
  const editTypeSelect = document.getElementById('editType');
  renderTypeSelect(editTypeSelect, types, currentNote['类型'] || '');
  // 加载笔记数据到表单
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${currentNote['主键']}/edit`);
    const result = await response.json();
    if (result.success) {
      document.getElementById('editTitle').value = result.data['标题'] || '';
      document.getElementById('editType').value = result.data['类型'] || '';
      document.getElementById('editKeyList').value = result.data['关键词'] || '';
      document.getElementById('editSource').value = result.data['来源'] || '';
      document.getElementById('editContent').value = result.data['内容'] || '';
      document.getElementById('editThink').value = result.data['思考'] || '';
    } else {
      alert('获取数据失败：' + result.message);
      mask.style.display = 'none';
    }
  } catch (e) {
    alert('获取数据失败：' + e.message);
    mask.style.display = 'none';
  }
}

// 关闭编辑模态框
function closeEditModal() {
  document.getElementById('editModalMask').style.display = 'none';
}

// 提交编辑表单
async function submitEditForm(e) {
  e.preventDefault();
  
  const id = document.getElementById('editId').value;
  const data = {
    title: document.getElementById('editTitle').value,
    type: document.getElementById('editType').value,
    key_list: document.getElementById('editKeyList').value,
    source: document.getElementById('editSource').value,
    content: document.getElementById('editContent').value,
    think: document.getElementById('editThink').value
  };
  
  try {
    const response = await fetch(`http://127.0.0.1:3000/api/notes/${id}/edit`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
    const result = await response.json();
    if (result.success) {
      alert('更新成功！');
      closeEditModal();
      // 重新加载当前笔记以显示更新后的内容
      await loadRandomNote();
    } else {
      alert('更新失败：' + result.message);
    }
  } catch (e) {
    alert('更新失败：' + e.message);
  }
}

// 键盘快捷键支持
document.addEventListener('keydown', function(event) {
  // 如果焦点在聊天输入框，不处理快捷键
  if (event.target.id === 'chatInput') {
    return;
  }
  
  switch(event.key) {
    case 'ArrowLeft':
    case 'ArrowRight':
      loadNewRandomNote(false);
      break;
    case ' ': // 空格键
      if (!currentNoteReviewed) {
        markAsReviewed();
      }
      break;
    case 'Enter': // 回车键
      if (!currentNoteReviewed) {
        markAsReviewed();
      }
      break;
    case 'Escape':
      window.close();
      break;
  }
});

// 初始化拖拽分隔条功能
function initResizer() {
  const resizer = document.getElementById('resizer');
  const leftPanel = document.getElementById('leftPanel');
  const rightPanel = document.getElementById('rightPanel');
  
  if (!resizer || !leftPanel || !rightPanel) {
    console.warn('拖拽分隔条元素未找到');
    return;
  }
  
  let isResizing = false;
  let startX, startLeftWidth;
  
  resizer.addEventListener('mousedown', function(e) {
    isResizing = true;
    startX = e.clientX;
    startLeftWidth = leftPanel.offsetWidth;
    
    // 禁用文本选择
    document.body.style.userSelect = 'none';
    document.body.style.cursor = 'col-resize';
    
    // 添加拖拽时的样式
    resizer.style.background = '#0056b3';
    resizer.querySelector('.resizer-handle').style.background = '#fff';
  });
  
  document.addEventListener('mousemove', function(e) {
    if (!isResizing) return;
    
    const containerWidth = leftPanel.parentNode.offsetWidth;
    const resizerWidth = resizer.offsetWidth;
    const deltaX = e.clientX - startX;
    
    // 计算新的左侧面板宽度
    let newLeftWidth = startLeftWidth + deltaX;
    
    // 设置最小和最大宽度限制
    const minLeftWidth = 400;
    const maxLeftWidth = containerWidth - 300 - resizerWidth; // 右侧最小300px
    
    newLeftWidth = Math.max(minLeftWidth, Math.min(maxLeftWidth, newLeftWidth));
    
    // 应用新宽度
    leftPanel.style.width = newLeftWidth + 'px';
    
    // 右侧面板自动填充剩余空间
    const rightWidth = containerWidth - newLeftWidth - resizerWidth;
    rightPanel.style.width = rightWidth + 'px';
  });
  
  document.addEventListener('mouseup', function() {
    if (!isResizing) return;
    
    isResizing = false;
    
    // 恢复样式
    document.body.style.userSelect = '';
    document.body.style.cursor = '';
    resizer.style.background = '';
    resizer.querySelector('.resizer-handle').style.background = '';
    
    // 保存宽度设置到本地存储
    const leftWidth = leftPanel.offsetWidth;
    const rightWidth = rightPanel.offsetWidth;
    localStorage.setItem('panelWidths', JSON.stringify({
      left: leftWidth,
      right: rightWidth
    }));
  });
  
  // 加载保存的宽度设置
  const savedWidths = localStorage.getItem('panelWidths');
  if (savedWidths) {
    try {
      const widths = JSON.parse(savedWidths);
      const containerWidth = leftPanel.parentNode.offsetWidth;
      const resizerWidth = resizer.offsetWidth;
      
      // 验证宽度是否合理
      if (widths.left >= 400 && widths.right >= 300 && 
          widths.left + widths.right + resizerWidth <= containerWidth) {
        leftPanel.style.width = widths.left + 'px';
        rightPanel.style.width = widths.right + 'px';
      }
    } catch (e) {
      console.log('加载面板宽度设置失败:', e);
    }
  }
}

// 构建笔记问答提示词
async function buildNoteQaPrompt(note, userQuestion) {
  try {
    // 直接使用嵌入的提示模板，避免文件读取问题
    let promptTemplate = `## 任务
1、当前用户正在浏览以下笔记内容，请参考笔记内容协助回答用户问题
2、如果笔记内容不足以支持用户的提问，或用户问了和笔记无关的问题，或用户希望你基于你的知识内容进行回答时，你需要基于你的经验知识进行回答

## 笔记内容
"""
{notes}
"""
## 用户问题
{question}`;
    
    // 构建笔记内容字符串
    const notesContent = `标题：${note['标题'] || '无标题'}
类型：${note['类型'] || '未分类'}
关键词：${note['关键词'] || '无'}
来源：${note['来源'] || '未知'}
内容：${note['内容'] || '暂无内容'}
思考：${note['思考'] || '暂无思考'}`;
    
    // 替换模板中的占位符
    promptTemplate = promptTemplate.replace(/{notes}/g, notesContent);
    promptTemplate = promptTemplate.replace(/{question}/g, userQuestion);
    
    return promptTemplate;
  } catch (error) {
    console.error('构建笔记问答提示失败:', error);
    throw error;
  }
}